<template>
  <div class="layui-row">
    <h1 class="threed">WebSocket服务端</h1>
    <div class="layui-col-md8 layui-col-md-offset2" style="margin-top: 20px">
      <h1 style="margin-top: 100px">服务端</h1>
      <div class="layui-card">
        <div class="layui-card-body-inline" style="padding-bottom: 20px">
          <div class="layui-form-item">
            <label class="layui-form-label">在线数量:<span id="sum">0</span></label>
          </div>

          <form class="layui-form" action="">
            <div class="layui-form-item">
              <label class="layui-form-label">在线人:</label>
              <div id="members">
              </div>
            </div>
          </form>

          <div class="layui-form-item">
            <label class="layui-form-label">信息内容:</label>
            <div class="layui-input-inline" style="width: 300px">
              <input id="msg" type="text" name="title" required lay-verify="required" placeholder="请输入要发送的内容"
                     autocomplete="off" class="layui-input">
            </div>
          </div>

          <button class="layui-btn" @click="sendMsg(1)">发送</button>
          <button class="layui-btn" @click="sendAll(1)">全部发送</button>
          <button class="rotary" @click="showRotary">开启大转盘</button>
        </div>
      </div>
      <div class="layui-card" style="margin-top: 100px">
        <div class="layui-card-header">
          <h1>操作详情</h1>
        </div>

        <div id="content" class="layui-card-body" placeholder="请输入要发送的内容">

        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "index",
    data() {
      return {
        websocketServerInfo: null,
        adminName: 'lg',
        ws:null,
        checkboxs : ""
      }
    },
    methods: {
      initServerConnect() {
        //服务器连接成功之后  再ajax调用controller 获得 最新的用户列表和人数
        var _this = this;
        $.ajax({
          url: "/api/configController/websocketServerInfo",
          type: "get",
          dataType: "json",
          success: function (dto) {
            _this.websocketServerInfo = dto.msg; //得到http服务器告知的 websocket服务器的地址
            _this.connect();//根据地址连接ws服务器


            window.setInterval(function(){

              _this.getUserList();
            },5000)

          }
        });
      },
      //获取服务器上的已连接的用户名
      getUserList() {
         var _this = this;
        $.ajax({
          url: this.$store.state.host+"/webSocketAdmin",
          type: "post",
          dataType: "json",
          success: function (dto) {
            var webSocketVos = dto.tList;
            var nums = dto.t;
            $("#sum").text(nums);

            console.log(webSocketVos);
            //勾选用户的用户名提交给服务器
            _this.checkboxs = "";
            for(var i=0;i<webSocketVos.length;i++) {
              var webSocketVo = webSocketVos[i];
              //console.log(webSocketVo);
              var flag = false;

              $("#members input").each(function (i, checkbox) {

                if ($(checkbox).attr('title') == webSocketVo) {
                  flag = true;
                  //报错，就跳出循环

                }
              });

              if (flag==false) {
                _this.checkboxs += webSocketVo + " <input type=\"checkbox\"  name=\"check\" title='" + webSocketVo + "'>";
              }
            }

            $("#members").append(_this.checkboxs);
          }
        });
      },
      sendMsg(code) {

        var users = "";
        $("input[name='check']:checked").each(function (i) {//把所有被选中的复选框的值存入数组
          users = users + $(this).attr("title") + ","
        });


        if (users.length > 0) {
          users = users.substr(0, users.length - 1);//只去掉最后一个逗号
        } else {
          this.$message.error("未选中客户");
          $("#content").html(content + '<div style="margin-bottom: 8px">\n' +
            '                        <p><q style="color: red">' + '系统提示:请在多选框中选择要发送的用户' + '</span></p>\n' +
            '                    </div>\n' +
            '                    <br/>');
          return
        }

        var msg = $("#msg").val();
        if(msg==null||msg==""){
          this.$message.error("请填写内容后再发送");
          return
        }
          $.ajax({
            method: 'get',
            url: this.$store.state.host+'/sendmsg',
            data: {
              "username": users,
              "msg": code+","+msg
            },
            success: function (data) {
              console.log(data);
              var content = $("#content").html();
              $("#content").html(content + '<div style="margin-bottom: 8px">\n' +
                '                        <p><q style="color: #eb7350">' + '服务器推送  ' + msg + ' -->' + users + '</span></p>\n' +
                '                    </div>\n' +
                '                    <br/>');
              console.log(data);
            }
          })

      },

      sendAll(code) {
        var msg = $("#msg").val();
        if(msg==null||msg==""){
          this.$message.error("请填写内容后再发送");
          return
        }
          $.ajax({
            method: 'get',
            url: this.$store.state.host+'/sendAll',
            data: {
              msg: code+","+msg
            },
            success: function (data) {
              $("#content").html(content + '<div style="margin-bottom: 8px">\n' +
                '                        <p><q style="color: #eb7350">' + '服务器推送  ' + msg + ' --> 所有用户' + '</span></p>\n' +
                '                    </div>\n' +
                '                    <br/>');
              console.log(data);
            }
          })

      },
//连接websocket服务器
      connect() {
        var _this = this;
        if ('WebSocket' in window) {
          this.ws = new WebSocket(this.websocketServerInfo + this.adminName);
        } else if ('MozWebSocket' in window) {
          this.ws = new MozWebSocket(this.websocketServerInfo + this.adminName);
        } else {
          alert("该浏览器不支持websocket");
        }
        this.ws.onmessage = function (evt) {
          var content = $("#content").html();
          $("#content").html(content + '<div style="text-align: right;margin-bottom: 8px">\n' +
            '                        <p><q style="color: mediumorchid;text-align: right">' + evt.data + '</span></p>\n' +
            '                    </div>\n' +
            '                    <br/>');
          console.log(msg)
        };

        this.ws.onclose = function (evt) {
          console.log('连接关闭')
        };

        this.ws.onopen = function (evt) {
          var content = $("#content").html();
          $("#content").html(content + '<div style="margin-bottom: 8px">\n' +
            '                        <p><q style="color: #eb7350">' + '服务器初始化成功...' + '</span></p>\n' +
            '                    </div>\n' +
            '                    <br/>');
          console.log('连接成功')
          _this.getUserList();//连接成功后获得服务器已连接的用户列表
        };
      },
      showRotary(){
        $("#msg").val("rotary()");
        this.sendAll(2);
      }

    },
    created() {//1.页面初始化 就连接websocket服务器
      this.initServerConnect();
    },

  }
</script>

<style scoped>
  .threed {
    text-align: center;
    color: #eb7350;
    -webkit-text-stroke: 1px black;
    letter-spacing: 0.04em;
    background-color: white;
  }
</style>
